
import React, { Component,useState,useRef,useEffect } from 'react';
import "./index.scss"
import { Tabs ,Form, Input, Button, Row ,Col } from 'antd';
import { UserOutlined, LockOutlined ,PhoneOutlined,MacCommandOutlined } from '@ant-design/icons';
import {passReg, phoneReg,smsReg,usernameReg} from "../../utils/validate"
import { ajax } from '../../api';
import {withRouter} from "react-router-dom"
import { showFail } from '../../api/http';

const { TabPane } = Tabs;


class Login extends Component {
    drawCanvas(){
        var canvas = document.getElementById('canvas'),
	    ctx = canvas.getContext('2d'),
	    w = canvas.width = window.innerWidth,
	    h = canvas.height = window.innerHeight,
	
	    hue = 217,
	    stars = [],
	    count = 0,
	    maxStars = 520;//��������

		var canvas2 = document.createElement('canvas'),
		ctx2 = canvas2.getContext('2d');
		canvas2.width = 100;
		canvas2.height = 100;
		
		var half = canvas2.width / 2,
		gradient2 = ctx2.createRadialGradient(half, half, 0, half, half, half);
		gradient2.addColorStop(0.025, '#CCC');
		gradient2.addColorStop(0.1, 'hsl(' + hue + ', 61%, 33%)');
		gradient2.addColorStop(0.25, 'hsl(' + hue + ', 64%, 6%)');
		gradient2.addColorStop(1, 'transparent');
		
		ctx2.fillStyle = gradient2;
		ctx2.beginPath();
		ctx2.arc(half, half, half, 0, Math.PI * 2);
		ctx2.fill();
		
		//End cache
		
		function random(min, max) {
		if (arguments.length < 2) {
		   max = min;
		   min = 0;
		}
		
		if (min > max) {
		   var hold = max;
		   max = min;
		   min = hold;
		}
		
		return Math.floor(Math.random() * (max - min + 1)) + min;
		}
		
		function maxOrbit(x, y) {
		var max = Math.max(x, y),
		 diameter = Math.round(Math.sqrt(max * max + max * max));
		return diameter / 2;
		//�����ƶ���Χ��ֵԽ��ΧԽС��
		}
		
		var Star = function () {
		
		this.orbitRadius = random(maxOrbit(w, h));
		this.radius = random(60, this.orbitRadius) / 8;
		//���Ǵ�С
		this.orbitX = w / 2;
		this.orbitY = h / 2;
		this.timePassed = random(0, maxStars);
		this.speed = random(this.orbitRadius) / 50000;
		//�����ƶ��ٶ�
		this.alpha = random(2, 10) / 10;
		
		count++;
		stars[count] = this;
		}
		
		Star.prototype.draw = function () {
		var x = Math.sin(this.timePassed) * this.orbitRadius + this.orbitX,
		 y = Math.cos(this.timePassed) * this.orbitRadius + this.orbitY,
		 twinkle = random(10);
		
		if (twinkle === 1 && this.alpha > 0) {
		   this.alpha -= 0.05;
		} else if (twinkle === 2 && this.alpha < 1) {
		   this.alpha += 0.05;
		}
		
		ctx.globalAlpha = this.alpha;
		ctx.drawImage(canvas2, x - this.radius / 2, y - this.radius / 2, this.radius, this.radius);
		this.timePassed += this.speed;
		}
		
		for (var i = 0; i < maxStars; i++) {
		new Star();
		}
		
		function animation() {
		ctx.globalCompositeOperation = 'source-over';
		ctx.globalAlpha = 0.8; //β��
		ctx.fillStyle = 'hsla(' + hue + ', 64%, 6%, 2)';
		ctx.fillRect(0, 0, w, h)
		
		ctx.globalCompositeOperation = 'lighter';
		for (var i = 1, l = stars.length; i < l; i++) {
		   stars[i].draw();
		   canvas2.style.cssText = "display:none";
		};
		
		window.requestAnimationFrame(animation);
		}
		
		
		animation();
    }

    componentDidMount(){
        this.drawCanvas()
    }
    render() {
        return (
            <div className="login">
                <canvas id="canvas"></canvas>
                <div className="login-box">
                <Tabs defaultActiveKey="1">
                    <TabPane tab="密码登录" key="1">
                        <LoginPassword></LoginPassword>
                    </TabPane>
                    <TabPane tab="手机登陆" key="2">
                        <LoginCaptcha history={this.props.history}></LoginCaptcha>
                    </TabPane>
                </Tabs>
                </div>
            </div>
        );
    }
}

export default Login;

const layout = {
    wrapperCol: { offset: 4, span: 16 },
};
const tailLayout = {
    wrapperCol: { offset: 6, span: 12 },
};
@withRouter
class LoginPassword extends Component{

    onFinish = (values) => {
        console.log( values);
        ajax.login(values).then(res=>{
            if(res.code==200){
                this.props.history.push("/main");
                localStorage.setItem("username",values.username)
                localStorage.setItem("token",res.token)
            }
        })
      };

    render(){
        return (
            <div>
                 <Form
                    name="normal_login"
                    className="login-form"
                    initialValues={{
                        
                    }}
                    {...layout}
                    onFinish={this.onFinish}
                    >
                    <Form.Item
                        name="username"
                        rules={[
                        {
                            required: true,
                            message: '请输入用户名',
                        },
                        {
                            pattern:usernameReg,message:"请填写2-4位的汉字姓名"
                        }
                        ]}
                    >
                        <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" />
                    </Form.Item>
                    <Form.Item
                        name="password"
                        rules={[
                        {
                            required: true,
                            message: '请输入密码',
                        },
                        {
                            pattern:passReg,
                            message:"请输入6-12位的合法密码"
                        }
                        ]}
                    >
                        <Input
                        prefix={<LockOutlined className="site-form-item-icon" />}
                        type="password"
                        placeholder="登录密码"
                        />
                    </Form.Item>
                    <Form.Item {...tailLayout}>
                        <Button block type="primary" htmlType="submit" className="login-form-button">
                            登录
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        )
    }
}


function LoginCaptcha({history}){
    const smsForm=useRef()
    let timer=null
    let [count,setCount] = useState(10)
    const [flag,setFlag] = useState(true)

    const countDown=()=>{
        if(count>0){
            setCount(--count);
            setFlag(false)
        }else{
            clearInterval(timer)
            timer=null;
            setCount(10);
            setFlag(true)
        }
    }

    const getCaptcha=()=>{
        var {phone} = smsForm.current.getFieldsValue()
        if(phoneReg.test(phone)){
            countDown()
            timer=setInterval(countDown,1000);
            ajax.getyanzhengma({phone:phone}).then(res=>{
                console.log(res)
            })
        }else{
            showFail("请填写正确的手机号码")
        }
    }

    const onFinish=(value)=>{
        ajax.getverify(value).then(res=>{
            console.log(res)
            if(res.code==200){
                history.push("/main");
                localStorage.setItem("username",res.username)
                localStorage.setItem("phone",res.phone)
                localStorage.setItem("token",res.token)
            }
        })
    }

    const onFinishFailed=()=>{

    }
    return(
        <div>
            <Form  
                className="login-form"
                name="loginform"
                {...layout}
                ref={smsForm}
                initialValues={{  

                }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
            >
                <Form.Item
                    name="phone"
                    rules={[
                        { required: true, message: '请输入手机号码' },
                        {pattern:phoneReg,message:"请输入正确手机号码"}
                    ]}
                    
                >
                    <Input type="tel"  placeholder="手机号码" prefix={<PhoneOutlined  className="login-icon-color"   />} />
                </Form.Item>

                <Form.Item
                    name="captcha"
                    rules={[{ required: true, message: '请输入验证码' },
                    {pattern:smsReg,message:"请输入4位验证码"}

                ]}
                >
                    <Row>
                        <Col span={14}>
                            <Input type="text"  placeholder="短信验证码" prefix={<MacCommandOutlined  className="login-icon-color"  />} />
                        </Col>
                            
                         <Col span={10}>
                            {
                               flag? (<Button block type="primary"  onClick={getCaptcha} >
                                获取验证码
                            </Button>):(<Button block type="danger" disabled>
                                {count} S
                            </Button>)
                            }
                        </Col>
                    </Row>
                </Form.Item>
                <Form.Item {...tailLayout}>
                    <Button block type="danger" htmlType="submit">
                        登录
                    </Button>
                </Form.Item>
            </Form>
        </div>
    )
}